﻿using ImageUploader;
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Common
{
    class tempMethod
    {
        private static byte[] _buffer = new byte[102400];
        private static int _receiveCount = 0;
        private static string _receiveString = string.Empty;
        ListBox listb_InfoList;
        private void ListenClientConnect(object listenSocket)
        {
            Socket clientSocket = (Socket)listenSocket;
            while (true)
            {
                // 等待连接
                Socket transferSocket = clientSocket.Accept();
                Thread thread = new Thread(ReceiveFile);
                thread.Start(transferSocket);
            }
        }
        private void ReceiveFile(object socket)
        {
            Socket transferSocket = (Socket)socket;

            try
            {
                var path = @"../../files";
                var tempCount = 0;
                var bpp = new BreakPointPost();
                while (true)
                {
                    if (ReceiveConsole(transferSocket) == "send argument")
                        break;
                }
                while (tempCount < 5)
                {
                    SetBreakPointPostArg(bpp, ReceiveConsole(transferSocket));
                    tempCount++;
                }
                ShowMsg.showMsg(listb_InfoList, "argument received.");
                path = Path.Combine(path, bpp.FileName);
                transferSocket.Send(Encoding.UTF8.GetBytes("argument received"));
                Thread.Sleep(100);
                while (true)
                {
                    _receiveCount = transferSocket.Receive(_buffer);
                    _receiveString = Encoding.UTF8.GetString(_buffer, 0, _receiveCount);
                    if (_receiveString == "start")
                    {
                        while (true)
                        {
                            _receiveCount = transferSocket.Receive(_buffer);
                            _receiveString = Encoding.UTF8.GetString(_buffer, 0, _receiveCount);
                            if (_receiveString.Contains("Index"))
                            {
                                SetBreakPointPostArg(bpp, _receiveString);
                                _buffer = new byte[bpp.PackageSize];
                                _receiveCount = transferSocket.Receive(_buffer);
                                if ((bpp.Index + 1) < bpp.PackageCount && _receiveCount != bpp.PackageSize)
                                    continue;
                                ShowMsg.showMsg(listb_InfoList, string.Format("{0} transform progress is {1}/{2}({3})", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), bpp.Index, bpp.PackageCount, _receiveCount));
                                FileWrite(path, bpp.Index, bpp.PackageSize, _receiveCount, _buffer);
                                transferSocket.Send(Encoding.UTF8.GetBytes("success|" + bpp.Index));
                                Thread.Sleep(100);
                                if (bpp.Index + 1 == bpp.PackageCount)
                                    break;
                            }
                            else if (_receiveString == "stop")
                            {
                                while (true)
                                {
                                    if (ReceiveConsole(transferSocket) == "restart")
                                        break;
                                }
                            }
                        }
                    }
                    if (bpp.Index + 1 == bpp.PackageCount)
                    {
                        bpp = null;
                        break;
                    }
                }
                while (true)
                {
                    if (ReceiveConsole(transferSocket) == "finish")
                        break;
                }
            }
            catch (Exception ex)
            {
                ShowMsg.showMsg(listb_InfoList, ex.Message);
            }
            finally
            {
                ShowMsg.showMsg(listb_InfoList, "disconnect...");
            }
        }

        private string ReceiveConsole(Socket socket)
        {
            _receiveCount = socket.Receive(_buffer);
            _receiveString = Encoding.UTF8.GetString(_buffer, 0, _receiveCount);
            ShowMsg.showMsg(listb_InfoList, "client : " + _receiveString);
            return _receiveString;
        }

        private static void SetBreakPointPostArg(BreakPointPost bpp, string value)
        {
            if (value.Contains("FileName"))
                bpp.FileName = value.Split('|')[1];
            if (value.Contains("FileSize"))
                bpp.FileSize = long.Parse(value.Split('|')[1]);
            if (value.Contains("PackageSize"))
                bpp.PackageSize = long.Parse(value.Split('|')[1]);
            if (value.Contains("PackageCount"))
                bpp.PackageCount = int.Parse(value.Split('|')[1]);
            if (value.Contains("Index"))
                bpp.Index = int.Parse(value.Split('|')[1]);
        }

        private static void FileWrite(string path, int index, long packageSize, int receiveSize, byte[] data)
        {
            using (System.IO.FileStream stream = System.IO.File.OpenWrite(path))
            {
                stream.Seek((long)index * (long)packageSize, System.IO.SeekOrigin.Begin);
                stream.Write(data, 0, receiveSize);
                stream.Flush();
            }
        }

        public class BreakPointPost
        {
            public string FileName { get; set; }
            public long FileSize { get; set; }
            public long PackageSize { get; set; }
            public int PackageCount { get; set; }
            public int Index { get; set; }
        }
    }
}
